package com.acic.jba.modules;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.pager.Pager;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.IocBy;
import org.nutz.mvc.annotation.Modules;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.ioc.provider.ComboIocProvider;

import com.acic.jba.bean.ComResponse;
import com.acic.jba.bean.Data;
import com.acic.jba.bean.Insurance;
import com.acic.jba.bean.Receipt;
import com.acic.jba.modules.common.BaseModule;
import com.assic.utils.db.SqlActuator;
import com.assic.utils.vo.Result;

@Modules(scanPackage = true)
@IocBy(type = ComboIocProvider.class, args = { "*org.nutz.ioc.loader.json.JsonLoader", "config/config.json", "*org.nutz.ioc.loader.annotation.AnnotationIocLoader", "com.acic.jba" })
@At("/")
@Fail("json")
public class MainModule extends BaseModule {

	@Inject
	private PropertiesProxy config;
	@Inject
	private PropertiesProxy sql;
	@Inject
	private Dao dao;

	/**
	 * 配置测试
	 * 
	 * @return
	 */
	@At("test")
	@Ok("json")
	public Result test() {
		return Result.success();
	}

	/**
	 * 报案入口
	 * 
	 * @param code
	 *            操作员好
	 * @param phone
	 *            报案电话
	 * @param recordId
	 *            录音Id
	 * @return
	 */
	@At("main")
	@Ok("jsp:jsp.main")
	public Result main(@Param("COperPrsnCode") String code, @Param("CRptPrsnMobile") String phone, @Param("Record_GUID") String recordId) {
		data.clear();
		List list = SqlActuator.runReportSql(sql.get("FETCH_CUSTOMER_BY_MOBILE").replaceAll("@phone@", phone), dao).getData();
		Pager pager = new Pager();
		pager.setPageNumber(1);
		pager.setPageSize(5);
		data.put("reportor", list.size() == 0 ? "" : ((Map) list.get(0)).get("NAME"));
		data.put("phone", phone == null ? "" : phone);
		data.put("optCode", code == null ? "" : code);
		data.put("rUid", recordId == null ? "" : recordId);
		List receipts = dao.query(Receipt.class, Cnd.where("reporterNo", "=", phone).and("reportTime", ">", Times.D(Times.format("yyyy-MM-dd", Times.now()))).desc("id"), pager);
		int count = receipts.size();
		for (int i = 0; i < 5 - count; i++) {
			receipts.add(new Receipt());
		}
		data.put("receipts", receipts);
		data.put(
				"count",
				SqlActuator.runReportSql("SELECT count(*) AS COUNT_ FROM JBA_RECEIPT_DETAIL where to_char(rpt_report_time) like '%" + Times.format("yyyy-MM-dd", Times.now())
						+ "%'", dao));
		return Result.success().setTitle("安诚接报案").setData(data);
	}

	/**
	 * 根据车牌加载承保详情
	 * 
	 * @param plate
	 *            车牌号
	 * @return 承保详情
	 */
	@At("plyInfo")
	@Ok("json")
	public Result queryPlyInfoByPlate(@Param("plate") String plate) {
		// 查询交强保单信息列表
		List jqInfos = SqlActuator.runReportSql(sql.get("FETCH_PLYINFO_BY_PLATE_AND_PLYTYPE").replaceAll("@plate@", plate).replaceAll("@plytype@", "0330"), dao).getData();
		// 查询商业保单信息列表
		List syInfos = SqlActuator.runReportSql(sql.get("FETCH_PLYINFO_BY_PLATE_AND_PLYTYPE").replaceAll("@plate@", plate).replaceAll("@plytype@", "0332"), dao).getData();
		String jqply = null;
		String syply = null;
		Insurance insurance = new Insurance();
		if (jqInfos.size() > 0) {
			Map infos = ((Map) jqInfos.get(0));
			jqply = infos.get("PLY_NO").toString();// 取得最新交强保单
			insurance.setJqPly(jqply);
			insurance.setJqBegin(Times.format("yyyy-MM-dd HH:mm:ss", Times.D(infos.get("BEGIN_TIME").toString())));
			insurance.setJqEnd(Times.format("yyyy-MM-dd HH:mm:ss", Times.D(infos.get("END_TIME").toString())));
			insurance.setJqEndTime(Times.D(infos.get("END_TIME").toString()).getTime());
		}
		if (syInfos.size() > 0) {
			Map infos = ((Map) syInfos.get(0));
			syply = infos.get("PLY_NO").toString();// 取得最新商业保单
			insurance.setSyPly(syply);
			insurance.setSyBegin(Times.format("yyyy-MM-dd HH:mm:ss", Times.D(infos.get("BEGIN_TIME").toString())));
			insurance.setSyEnd(Times.format("yyyy-MM-dd HH:mm:ss", Times.D(infos.get("END_TIME").toString())));
			insurance.setSyEndTime(Times.D(infos.get("END_TIME").toString()).getTime());
			NutMap syInfos_ = new NutMap();
			for (Map map : SqlActuator.runReportSql(sql.get("FETCH_CVRG").replaceAll("@plyno@", syply), dao).getData()) {
				syInfos_.put(decode(map.get("C_CVRG_NO").toString()), true);
			}
			insurance.setSyInfos(syInfos_);
		}
		data.clear();
		data.put("info", insurance);
		data.put("car", SqlActuator.runReportSql(sql.get("FETCH_CARINFO_BY_PLATE").replaceAll("@plate@", plate), dao));
		return Result.success().setData(data);
	}

	@At("loadPlys")
	@Ok("json")
	public Result loadPlys(@Param("plate") String plate, @Param("type") String type) {
		List infos = SqlActuator.runReportSql(sql.get("FETCH_PLYINFO_BY_PLATE_AND_PLYTYPE").replaceAll("@plate@", plate).replaceAll("@plytype@", type), dao).getData();
		data.clear();
		data.put("infos", infos);
		System.err.println(data);
		return Result.success().setData(data);
	}

	@At("plyInfoByCus")
	@Ok("json")
	public Result plyInfoByCus(@Param("cusNo") String cusNo) {
		// 查询交强保单信息列表
		List jqInfos = SqlActuator.runReportSql(sql.get("FETCH_PLYINFO_CUS_NO_AND_PLYTYPE").replaceAll("@cusno@", cusNo).replaceAll("@plytype@", "0330"), dao).getData();
		// 查询商业保单信息列表
		List syInfos = SqlActuator.runReportSql(sql.get("FETCH_PLYINFO_CUS_NO_AND_PLYTYPE").replaceAll("@cusno@", cusNo).replaceAll("@plytype@", "0332"), dao).getData();
		String jqply = null;
		String syply = null;
		Insurance insurance = new Insurance();
		if (jqInfos.size() > 0) {
			Map infos = ((Map) jqInfos.get(0));
			jqply = infos.get("PLY_NO").toString();// 取得最新交强保单
			insurance.setJqPly(jqply);
			insurance.setJqBegin(Times.format("yyyy/MM/dd HH:mm:ss", Times.D(infos.get("BEGIN_TIME").toString())));
			insurance.setJqEnd(Times.format("yyyy/MM/dd HH:mm:ss", Times.D(infos.get("END_TIME").toString())));
			insurance.setJqEndTime(Times.D(infos.get("END_TIME").toString()).getTime());
		}
		if (syInfos.size() > 0) {
			Map infos = ((Map) syInfos.get(0));
			syply = infos.get("PLY_NO").toString();// 取得最新商业保单
			insurance.setSyPly(syply);
			insurance.setSyBegin(Times.format("yyyy/MM/dd HH:mm:ss", Times.D(infos.get("BEGIN_TIME").toString())));
			insurance.setSyEnd(Times.format("yyyy/MM/dd HH:mm:ss", Times.D(infos.get("END_TIME").toString())));
			insurance.setSyEndTime(Times.D(infos.get("END_TIME").toString()).getTime());
			NutMap syInfos_ = new NutMap();
			for (Map map : SqlActuator.runReportSql(sql.get("FETCH_CVRG").replaceAll("@plyno@", syply), dao).getData()) {
				syInfos_.put(decode(map.get("C_CVRG_NO").toString()), true);
			}
			insurance.setSyInfos(syInfos_);
		}
		data.clear();
		data.put("info", insurance);
		return Result.success().setData(data);
	}

	@At("plyInfoByPly")
	@Ok("json")
	public Result plyInfoByPly(@Param("jq") String jq, @Param("sy") String sy) {
		// 查询交强保单信息列表
		List jqInfos = SqlActuator.runReportSql(sql.get("FETCH_PLYINFO_PLY_TYPE").replaceAll("@ply@", jq).replaceAll("@plytype@", "0330"), dao).getData();
		// 查询商业保单信息列表
		List syInfos = SqlActuator.runReportSql(sql.get("FETCH_PLYINFO_PLY_TYPE").replaceAll("@ply@", sy).replaceAll("@plytype@", "0332"), dao).getData();
		String jqply = null;
		String syply = null;
		Insurance insurance = new Insurance();
		if (jqInfos.size() > 0) {
			Map infos = ((Map) jqInfos.get(0));
			jqply = infos.get("PLY_NO").toString();// 取得最新交强保单
			insurance.setJqPly(jqply);
			insurance.setJqBegin(Times.format("yyyy/MM/dd HH:mm:ss", Times.D(infos.get("BEGIN_TIME").toString())));
			insurance.setJqEnd(Times.format("yyyy/MM/dd HH:mm:ss", Times.D(infos.get("END_TIME").toString())));
			insurance.setJqEndTime(Times.D(infos.get("END_TIME").toString()).getTime());
		}
		if (syInfos.size() > 0) {
			Map infos = ((Map) syInfos.get(0));
			syply = infos.get("PLY_NO").toString();// 取得最新商业保单
			insurance.setSyPly(syply);
			insurance.setSyBegin(Times.format("yyyy/MM/dd HH:mm:ss", Times.D(infos.get("BEGIN_TIME").toString())));
			insurance.setSyEnd(Times.format("yyyy/MM/dd HH:mm:ss", Times.D(infos.get("END_TIME").toString())));
			insurance.setSyEndTime(Times.D(infos.get("END_TIME").toString()).getTime());
			NutMap syInfos_ = new NutMap();
			for (Map map : SqlActuator.runReportSql(sql.get("FETCH_CVRG").replaceAll("@plyno@", syply), dao).getData()) {
				syInfos_.put(decode(map.get("C_CVRG_NO").toString()), true);
			}
			insurance.setSyInfos(syInfos_);
		}
		data.clear();
		data.put("info", insurance);
		return Result.success().setData(data);
	}

	@At("receipt")
	@Ok("jsp:jsp.receipt")
	public Result receipt(@Param("id") int id) {
		data.clear();
		data.put("receipt", dao.fetch(Receipt.class, id));
		return Result.success().setData(data);
	}

	/**
	 * 险种编码解码
	 * 
	 * @param code
	 *            保险编号
	 * @return 简拼描述
	 */
	private String decode(String code) {
		switch (code) {
		case "030018":
			return "syszx";
		case "030105":
			return "blpsx";
		case "030057":
			return "clzrx";
		case "030102":
			return "qcdqx";
		case "030210":
			return "sjzwx";
		case "030006":
			return "csx";
		case "030212":
			return "ckzwx";
		default:
			break;
		}
		return null;
	}

	/**
	 * 车牌自动完成
	 * 
	 * @param key
	 *            关键词
	 * @return 自动完成数据对象
	 */
	@At("queryPlate")
	@Ok("json")
	public ComResponse queryPlate(@Param("key") String key) {
		key = key.toUpperCase();
		List<Data> datas = new ArrayList<Data>();
		for (Map map : SqlActuator.runReportSql(sql.get("AUTO_TIP_PLATE").replaceAll("@key@", key.toUpperCase()), dao).getData()) {
			datas.add(new Data(map.get("C_CAR_PLATE").toString(), map.get("C_CAR_PLATE").toString()));
		}
		return new ComResponse(key, datas);
	}

	@At("queryMobile")
	@Ok("json")
	public ComResponse queryMobile(@Param("key") String key) {
		key = key.toUpperCase();
		List<Data> datas = new ArrayList<Data>();
		for (Map map : SqlActuator.runReportSql(sql.get("FETCH_MOBILES").replaceAll("@mobile@", key), dao).getData()) {
			datas.add(new Data(map.get("C_CUS_MOBILE").toString(), map.get("C_CUS_MOBILE").toString()));
		}
		return new ComResponse(key, datas);
	}

	@At("queryPlyNo")
	@Ok("json")
	public ComResponse queryPlyNo(@Param("key") String key) {
		key = key.toUpperCase();
		List<Data> datas = new ArrayList<Data>();
		for (Map map : SqlActuator.runReportSql(sql.get("FETCH_PLYNOS").replaceAll("@plyno@", key), dao).getData()) {
			datas.add(new Data(map.get("C_PLY_NO").toString(), map.get("C_PLY_NO").toString()));
		}
		return new ComResponse(key, datas);
	}

	/**
	 * VIN码自动完成
	 * 
	 * @param key
	 *            关键词
	 * @return 自动完成数据对象
	 */
	@At("queryVin")
	@Ok("json")
	public ComResponse queryVin(@Param("key") String key) {
		key = key.toUpperCase();
		List<Data> datas = new ArrayList<Data>();
		for (Map map : SqlActuator.runReportSql(sql.get("FETCH_VINS").replaceAll("@vin@", key), dao).getData()) {
			datas.add(new Data(map.get("C_CAR_VIN").toString(), map.get("C_CAR_VIN").toString()));
		}
		return new ComResponse(key, datas);
	}

	/**
	 * 发动机号自动完成
	 * 
	 * @param key
	 *            关键词
	 * @return 自动完成数据对象
	 */
	@At("queryEngine")
	@Ok("json")
	public ComResponse queryEngine(@Param("key") String key) {
		key = key.toUpperCase();
		List<Data> datas = new ArrayList<Data>();
		for (Map map : SqlActuator.runReportSql(sql.get("FERCH_ENGINES").replaceAll("@engine@", key), dao).getData()) {
			datas.add(new Data(map.get("C_CAR_ENGINE").toString(), map.get("C_CAR_ENGINE").toString()));
		}
		return new ComResponse(key, datas);
	}

	/**
	 * 品牌型号自动完成
	 * 
	 * @param key
	 *            关键词
	 * @return 自动完成数据对象
	 */
	@At("queryModel")
	@Ok("json")
	public ComResponse queryModel(@Param("key") String key) {
		key = key.toUpperCase();
		List<Data> datas = new ArrayList<Data>();
		for (Map map : SqlActuator.runReportSql(sql.get("FETCH_MODELS").replaceAll("@model@", key), dao).getData()) {
			datas.add(new Data(map.get("C_CAR_MODEL").toString(), map.get("C_CAR_MODEL").toString()));
		}
		return new ComResponse(key, datas);
	}

	/**
	 * 车主姓名自动完成
	 * 
	 * @param key
	 *            关键词
	 * @return 自动完成数据对象
	 */
	@At("queryName")
	@Ok("json")
	public ComResponse queryName(@Param("key") String key) {
		key = key.toUpperCase();
		List<Data> datas = new ArrayList<Data>();
		for (Map map : SqlActuator.runReportSql(sql.get("FETCH_CUS_NAME").replaceAll("@name@", key), dao).getData()) {
			datas.add(new Data(map.get("C_CUS_NME").toString(), map.get("C_CUS_NME").toString()));
		}
		return new ComResponse(key, datas);
	}

	/**
	 * 车主证件自动完成
	 * 
	 * @param key
	 *            关键词
	 * @return 自动完成数据对象
	 */
	@At("queryCert")
	@Ok("json")
	public ComResponse queryCert(@Param("key") String key) {
		key = key.toUpperCase();
		List<Data> datas = new ArrayList<Data>();
		for (Map map : SqlActuator.runReportSql(sql.get("FETCH_CERT_NO").replaceAll("@certno@", key), dao).getData()) {
			datas.add(new Data(map.get("C_CERT_NO").toString(), map.get("C_CERT_NO").toString()));
		}
		return new ComResponse(key, datas);
	}

	/**
	 * 根据vin码信息获取车辆信息
	 * 
	 * @param vin
	 *            vin码
	 * @return
	 */
	@At("listCarInfoByVin")
	@Ok("json")
	public Result listCarInfoByVin(@Param("vin") String vin) {
		data.clear();
		data.put("cars", SqlActuator.runReportSql(sql.get("FETCH_CARINFO_BY_VIN").replaceAll("@vin@", vin), dao));
		return Result.success().setData(data);
	}

	@At("listCarInfoByPlyNo")
	@Ok("json")
	public Result listCarInfoByPlyNo(@Param("plyNo") String plyNo) {
		data.clear();
		data.put("cars", SqlActuator.runReportSql(sql.get("FETCH_CARINFO_BY_PLY_NO").replaceAll("@plyNo@", plyNo), dao));
		return Result.success().setData(data);
	}

	/**
	 * 根据vin码信息获取车辆信息
	 * 
	 * @param vin
	 *            vin码
	 * @return
	 */
	@At("listCarInfoByEngine")
	@Ok("json")
	public Result listCarInfoByEngine(@Param("engine") String engine) {
		data.clear();
		data.put("cars", SqlActuator.runReportSql(sql.get("FETCH_CARINFO_BY_ENGINE").replaceAll("@engine@", engine), dao));
		return Result.success().setData(data);
	}

	@At("listCarInfoByMobile")
	@Ok("json")
	public Result listCarInfoByMobile(@Param("mobile") String mobile) {
		data.clear();
		data.put("cars", SqlActuator.runReportSql(sql.get("FETCH_CARINFO_BY_MOBILE").replaceAll("@mobile@", mobile), dao));
		return Result.success().setData(data);
	}

	/**
	 * 根据vin码信息获取车辆信息
	 * 
	 * @param vin
	 *            vin码
	 * @return
	 */
	@At("listCarInfoByModel")
	@Ok("json")
	public Result listCarInfoByModel(@Param("model") String model) {
		data.clear();
		data.put("cars", SqlActuator.runReportSql(sql.get("FETCH_CARINFO_BY_MODEL").replaceAll("@model@", model), dao));
		return Result.success().setData(data);
	}

	/**
	 * 根据vin码信息获取车辆信息
	 * 
	 * @param vin
	 *            vin码
	 * @return
	 */
	@At("listCarInfoByName")
	@Ok("json")
	public Result listCarInfoByName(@Param("name") String name) {
		data.clear();
		data.put("cars", SqlActuator.runReportSql(sql.get("FETCH_CARINFO_BY_NAME").replaceAll("@name@", name), dao));
		return Result.success().setData(data);
	}

	@At("listCarInfoByCert")
	@Ok("json")
	public Result listCarInfoByCert(@Param("certno") String certno) {
		data.clear();
		data.put("cars", SqlActuator.runReportSql(sql.get("FETCH_CARINFO_BY_CERT").replaceAll("@certno@", certno), dao));
		return Result.success().setData(data);
	}

	/**
	 * 
	 * @return 数据库信息探针
	 */
	@At("dbInfo")
	@Ok("json")
	public Result dbInfo() {
		data.clear();
		data.put("db-meta", dao.meta());
		return Result.success().setData(data);
	}

	/**
	 * 初始化数据表
	 * 
	 * @return
	 */
	@At("init")
	@Ok("json")
	public Result init(@Param("del") String del) {
		dao.create(Receipt.class, del != null);
		return Result.success();
	}

	@At("submit")
	@Ok("json")
	public Result submit(@Param("receipt") Receipt receipt) {
		String dellInfo = "报案成功";
		if (receipt.isDellFlag()) {
			dellInfo = "报案成功,正在派工";
		} else if (Strings.isEmpty(receipt.getValidBizPlyNo()) && Strings.isEmpty(receipt.getValidTraPlyNo())) {
			dellInfo = "无保单报案";
		} else if (!receipt.isAvailableFlag()) {
			dellInfo = "保单已过期,不予派工";
		} else {
			dellInfo = "事故责任不属于承保范围,不予派工";
		}
		receipt.setDellStatus(dellInfo);
		Receipt target = dao.insert(receipt);
		data.clear();
		data.put("receipt", target);
		return target == null ? Result.fail("保存报案信息失败") : Result.success().setData(data);
	}

	@At("confirmIncome")
	@Ok("json")
	public Result confirmIncome(@Param("id") int id) {
		Receipt receipt = dao.fetch(Receipt.class, id);
		receipt.setIncomeTimes(receipt.getIncomeTimes() + 1);
		return dao.update(receipt) == 1 ? Result.success() : Result.fail("更新数据失败");
	}

	@At("force")
	@Ok("json")
	public Result force(@Param("id") int id) {
		Receipt receipt = dao.fetch(Receipt.class, id);
		receipt.setDellStatus("强制派工成功,正在派工");
		receipt.setDellFlag(true);
		receipt.setIncomeTimes(receipt.getIncomeTimes() + 1);
		return dao.update(receipt) == 1 ? Result.success() : Result.fail("更新数据失败");
	}

	@At("runSql")
	@Ok("json")
	public Result runSql(@Param("sql") String sql) {
		sql = sql.toUpperCase();
		if (!sql.startsWith("SELECT")) {
			return Result.fail("没有执行: '" + sql +" ' 的权限" );
		}
		try {
			data.clear();
			data.put("result", SqlActuator.runReportSql(sql, dao));
			return Result.success().setData(data);
		} catch (Exception e) {
			return Result.fail(e.getMessage());
		}
	}

}
